package com.simpd.activity;

import java.util.ArrayList;

import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpResponseException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import cn.pedant.SweetAlert.SweetAlertDialog;

import com.another.helper.Logger;
import com.example.simpd.R;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.simpd.db_helper.DatabaseHelper;
import com.simpd.http_helper.CustomHttpClient;
import com.simpd.model.NotifikasiSKPD;
import com.simpd.model.ServerSimpd;

public class DetailNotifikasiActivity extends Activity{
	WebView browser; 
	
	FloatingActionButton btnSetujui; 
	FloatingActionButton btnTolak; 
	FloatingActionButton btnIsiKet; 
	FloatingActionButton btnKosongi; 
	FloatingActionButton btnSimpan; 
	FloatingActionButton btnShowKet; 
	
	ImageButton btnBack;
	
	FloatingActionsMenu btnMenu;
	ProgressBar progressBar;
	private SweetAlertDialog loadingDialog;
	
	// private static final String DEFAULT_URL = "http://sppd.gorontaloprov.go.id/simpd/rencanaPD/cetakSppd/ttd/id/12251?unip=";
	private static final String KEPADA		= "kepada"; 
	private static final String PENGAJU		= "pengaju";

	private String SERVER_URL = "http://sppd.gorontaloprov.go.id/simpd";
	
	private String result;
	
	private String errorTitle;
	private String errorMessage;
	private String unip;
	private String url;
	private String keterangan = "";
	
	private int id;
	private int location;
	
	private NotifikasiSKPD notifikasi;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		getActionBar().hide();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail_notifikasi);
		
		unip 		= getIntent().getExtras().getString("unip", "196206062012011001_default");
		url  		= getIntent().getExtras().getString("url","error");
		id 	 		= getIntent().getExtras().getInt("id", 1);
		location 	= getIntent().getExtras().getInt("position");
		browser    	= (WebView) findViewById(R.id.detail_notifikasi_webview);
			
		
		progressBar = (ProgressBar) findViewById(R.id.detail_notif_progressbar);
		progressBar.setMax(100);
		
		btnBack		= (ImageButton) findViewById(R.id.detail_notifikasi_back);
		
		DatabaseHelper db = new DatabaseHelper(this); 
		ServerSimpd server = db.getServer(); 
		SERVER_URL = server.getServerUrl();
		// Toast.makeText(this, SERVER_URL+url+"?unip="+unip, Toast.LENGTH_SHORT).show();
		notifikasi = db.getNotifikasi(id);
		Log.d("[stattus notifikasi]", "status notifikasi : "+notifikasi.getStatus());
		
		this.keterangan = notifikasi.getKeterangan();
		
		if (notifikasi.getStatus() != 2) {
			if(notifikasi.getSebagai().equalsIgnoreCase(KEPADA)){
				// set button for kepada
				btnSetujui  = (FloatingActionButton) findViewById(R.id.detail_notifikasi_action_setujui_kepada); 
				btnTolak	= (FloatingActionButton) findViewById(R.id.detail_notifikasi_action_tolak_kepada); 
				btnIsiKet	= (FloatingActionButton) findViewById(R.id.detail_notifikasi_action_isi_ket_kepada); 
				btnKosongi	= (FloatingActionButton) findViewById(R.id.detail_notifikasi_action_kosongi_kepada); 
				btnSimpan	= (FloatingActionButton) findViewById(R.id.detail_notifikasi_action_simpan_kepada); 
				
				btnMenu		= (FloatingActionsMenu) findViewById(R.id.detail_notifikasi_button_menu_kepada);
				btnMenu.setVisibility(View.VISIBLE);
				setMenuKepada();
			}else if(notifikasi.getSebagai().equalsIgnoreCase(PENGAJU)){
				// set button for pengaju
				btnSetujui  = (FloatingActionButton) findViewById(R.id.detail_notifikasi_action_setujui_pengaju); 
				btnKosongi	= (FloatingActionButton) findViewById(R.id.detail_notifikasi_action_kosongi_pengaju); 
				btnSimpan	= (FloatingActionButton) findViewById(R.id.detail_notifikasi_action_simpan_pengaju); 
				btnIsiKet 	= (FloatingActionButton) findViewById(R.id.detail_notifikasi_action_isi_ket_pengaju);
				
				btnMenu		= (FloatingActionsMenu) findViewById(R.id.detail_notifikasi_button_menu_pengaju);
				btnMenu.setVisibility(View.VISIBLE);
				
				setMenuPengaju();
			}
		}
		
		
		btnShowKet = (FloatingActionButton) findViewById(R.id.detail_notifikasi_show_ket); 
		btnShowKet.setIcon(R.drawable.icon_notebook_white);
		Log.d("[keterangan]", "nilai keterangan: "+keterangan);
		Log.d("[keterangan check]", "keterangan equals '' "+(this.keterangan.equals("")));
		
		if(!this.keterangan.equals("") && notifikasi.getSebagai().equalsIgnoreCase(PENGAJU)){
			btnShowKet.setVisibility(View.VISIBLE);
			btnShowKet.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					displayKeterangan();
				}
			});
		}else {
			btnShowKet.setVisibility(View.GONE);
			Log.d("[keterangan inside]", "jika keterangan kosong");
			if(notifikasi.getStatus() != DatabaseHelper.STATUS_SIGNATURE){
				DisplayMetrics dm = this.getResources().getDisplayMetrics(); 
				int dpi  = dm.densityDpi;
				int dp   = 18;
				float displayConstant = 160; 
				int bottom =(int) (dp * (float)(dpi/displayConstant));
				RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) btnMenu.getLayoutParams();
				params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); 
				params.bottomMargin = bottom; 
				btnMenu.setLayoutParams(params);
			}
		}
			
		
		btnBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		try {

			browser.loadUrl(SERVER_URL+url+"?unip="+unip);
			Log.d("[browsing]", "render address : "+ SERVER_URL+url+"?unip="+unip);
			browser.getSettings().setBuiltInZoomControls(true);
			browser.getSettings().setUseWideViewPort(true);
			browser.getSettings().setDisplayZoomControls(false);
			browser.getSettings().setJavaScriptEnabled(true);
			browser.setWebChromeClient(new MyWebChromeClient());
			browser.getSettings().setPluginState(PluginState.ON);
			browser.addJavascriptInterface(new MyJavaScriptInterface(getApplicationContext()), "AndroidFunction");
		} catch (Exception e) {
			SweetAlertDialog alert = new SweetAlertDialog(getApplicationContext(), SweetAlertDialog.ERROR_TYPE); 
			alert.setTitleText("Oops...!!");
			alert.setContentText("terjadi kesalahan : "+e.getMessage());
			alert.show(); 
			e.printStackTrace(); 
			Logger.e(DetailNotifikasiActivity.this, "error webview", e.toString());
		}
		
	}
	
	
	private void setMenuKepada(){
		btnSetujui.setIcon(R.drawable.icon_signature_flat);
		btnSetujui.setTitle("Setujui"); 
		btnSetujui.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionSetujui();
				btnMenu.toggle();
			}
		});
		
		btnTolak.setIcon(R.drawable.icon_disapprove_white);
		btnTolak.setTitle("Tolak"); 
		btnTolak.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionTolak();
				btnMenu.toggle();
			}
		});
		
		btnIsiKet.setIcon(R.drawable.icon_write_white);
		btnIsiKet.setTitle("Isi Keterangan"); 
		btnIsiKet.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionIsiKeterangan();
				btnMenu.toggle();
			}
		});
		
		
		setMenuKosongiDanSimpan();
	}
	
	private void setMenuPengaju(){
		
		btnSetujui.setIcon(R.drawable.icon_signature_flat);
		btnSetujui.setTitle("Tanda tangani"); 
		btnSetujui.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionTandaTangani();
				btnMenu.toggle();
			}
		});
		
		btnIsiKet.setIcon(R.drawable.icon_write_white);
		btnIsiKet.setTitle("Isi Keterangan"); 
		btnIsiKet.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showInputKeterangan();
				btnMenu.toggle();
			}
		});
		
		setMenuKosongiDanSimpan();
		
	}
	
	private void setMenuKosongiDanSimpan(){
		btnKosongi.setIcon(R.drawable.icon_eraser_white);
		btnKosongi.setTitle("Kosongi"); 
		btnKosongi.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionKosongi();
				btnMenu.toggle();
			}
		});
		
		btnSimpan.setIcon(R.drawable.icon_save_white);
		btnSimpan.setTitle("Simpan"); 
		btnSimpan.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionSimpan();
				btnMenu.toggle();
			}
		});
	}
	
	private void displayKeterangan(){
		final SweetAlertDialog alertKeterangan = new SweetAlertDialog(DetailNotifikasiActivity.this, 
				   SweetAlertDialog.NORMAL_TYPE);
		alertKeterangan.setTitleText("Keterangan"); 
		alertKeterangan.setContentText(notifikasi.getKeterangan());
		alertKeterangan.setContentTextSize(16);
		alertKeterangan.setCancelText("Tutup"); 
		alertKeterangan.setConfirmText("Edit"); 
		alertKeterangan.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
		
			@Override
			public void onClick(SweetAlertDialog sweetAlertDialog) {
				alertKeterangan.dismiss();
			}
		});
		
		alertKeterangan.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
		
			@Override
			public void onClick(SweetAlertDialog sweetAlertDialog) {
				alertKeterangan.dismiss(); 
				showInputKeterangan();
			}
		});
		
		alertKeterangan.show();
	}
	
	private void showInputKeterangan(){
		LayoutInflater inflater = DetailNotifikasiActivity.this.getLayoutInflater();
		
		
		AlertDialog.Builder builder = new AlertDialog.Builder(DetailNotifikasiActivity.this); 
		// builder.setTitle("Isi Keterangan");
		// builder.setMessage("Silahkan isikan keterangan untuk dokumen ini!"); 
		// set an edit text view to get user input
		// final EditText input = new EditText(DetailNotifikasiActivity.this);
		View dialogView = inflater.inflate(R.layout.dialog_keterangan, null);
		final EditText inputKeterangan = (EditText) dialogView.findViewById(R.id.dialog_keterangan_input_text);
		inputKeterangan.setText(keterangan);
		inputKeterangan.setSelection(inputKeterangan.getText().toString().length());
		builder.setView(dialogView);
		
		builder.setPositiveButton("Simpan", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				keterangan = inputKeterangan.getText().toString();
				DatabaseHelper db = new DatabaseHelper(DetailNotifikasiActivity.this); 
				notifikasi.setKeterangan(keterangan);
				db.update(notifikasi.getId(), notifikasi);
				
				SweetAlertDialog alert = new SweetAlertDialog(DetailNotifikasiActivity.this, SweetAlertDialog.SUCCESS_TYPE);
				alert.setTitleText("Berhasil!");
				alert.setContentText("Keterangan berhasil disimpan!"); 
				alert.show();
			}
		});
		
		builder.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		
		AlertDialog alert = builder.create();
		alert.show();
	}

	
	private void actionKosongi(){
		browser.loadUrl("javascript:resetTtd()");
	}
	private void actionTandaTangani(){
		browser.loadUrl("javascript:turnOnTtd('signaturePengaju')");
		browser.loadUrl("javascript:setAon('dari')");
	}
	
	private void actionSetujui(){
		browser.loadUrl("javascript:resetTtd()");
		browser.loadUrl("javascript:turnOnTtd('signatureSetuju')");
		browser.loadUrl("javascript:setAon('setuju')");
	}
	
	private void actionTolak(){
		browser.loadUrl("javascript:resetTtd()");
		browser.loadUrl("javascript:turnOnTtd('signatureTolak')");
		browser.loadUrl("javascript:setAon('tidak')");
	}
	private void actionIsiKeterangan(){
		browser.loadUrl("javascript:turnOnTtd('signatureKeterangan')");
		browser.loadUrl("javascript:setAket('true')");
	}
	
	private void actionSimpan(){
		Log.d("[trying-run javascript]", "trying run javascript getSaveParam()");
		browser.loadUrl("javascript:getSaveParam()");
	}

	
	public class MyJavaScriptInterface{
		Context context; 
		public MyJavaScriptInterface(Context context) {
			this.context = context;
		}
		
		public void getSaveParam(String param){
			try {
				
				JSONObject paramTtd = new JSONObject(param);
				if(notifikasi.getSebagai().equalsIgnoreCase(PENGAJU)){
					JSONObject data =  paramTtd.getJSONObject("data");
					data.put("keterangan", keterangan); 
					paramTtd.put("data", data); 
				}
				String paramTtd2String = paramTtd.toString();
				
				/*AlertDialog.Builder builder = new AlertDialog.Builder(DetailNotifikasiActivity.this); 
				builder.setTitle("json text"); 
				builder.setMessage(param+"\n insert keterangan : \n"+paramTtd2String); 
				
				AlertDialog alert = builder.create(); 
				alert.show();*/
				
				Log.d("[run getSavedParam]", "android function just run!!");
				DatabaseHelper db = new DatabaseHelper(DetailNotifikasiActivity.this); 
				ServerSimpd server = db.getServer(); 
				
				
				url = server.getServerUrl()+"/site/ttd_save";
				// Toast.makeText(DetailNotifikasiActivity.this, "sent parameter to : "+url, Toast.LENGTH_SHORT).show();
				ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>(); 
				parameters.add(new BasicNameValuePair("unip", unip));
				parameters.add(new BasicNameValuePair("ttd", paramTtd2String));
				
				Thread thread = new Thread(new SaveTtdThread(url, parameters));
				thread.start();
				Log.d("object", "object class : "+param.getClass());
			} catch (Exception e) {
				SweetAlertDialog alert = new SweetAlertDialog(DetailNotifikasiActivity.this, SweetAlertDialog.ERROR_TYPE);
				alert.setTitleText("Oops...!");
				alert.setContentText("Terjadi kesalahan karena : " + e.getMessage());
				alert.show();
				Log.e("[error]", "error with exception : "+e.toString());
				
				/*StringWriter errorWriter = new StringWriter(); 
				e.printStackTrace(new PrintWriter(errorWriter));*/
				e.printStackTrace();
				Logger.e(DetailNotifikasiActivity.this, "error calling js func.", e.toString());
				
			}
			
		}
	}
	
	private class MyCustomWebViewClient extends WebViewClient{ 
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}
		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			progressBar.setVisibility(View.VISIBLE);
			super.onPageStarted(view, url, favicon);
		}
		
		@Override
		public void onPageFinished(WebView view, String url) {
			progressBar.setVisibility(View.GONE);
			super.onPageFinished(view, url);
		}
	}
	
	private class MyWebChromeClient extends WebChromeClient{
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			DetailNotifikasiActivity.this.setValue(newProgress);
			super.onProgressChanged(view, newProgress);
		}
	}
	
	
	private void setValue(int progress){
		if(progress >= 100){
			this.progressBar.setVisibility(View.GONE);
		}else{
			this.progressBar.setProgress(progress);
		}
	}
	
	private boolean saveTtdUsingThread(final String url, final ArrayList<NameValuePair> postParameters){
		boolean successful = false;
		
		String response = null;
		result 	= null;
		
		errorTitle = null; 
		errorMessage = null;
		
		Log.d("[url]", "url : "+url);
		Log.d("[post-params]", "unip : "+postParameters.get(0).getValue()+", " +
							   "ttd : "+postParameters.get(1).getValue()+"");
		try {
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			result = response.toString(); 
			Log.d("[save-ttd-result]", "result saved ttd : "+result);
			successful = true;
		}catch (HttpResponseException e) {
			errorTitle = "HttpResponseException"; 
			errorMessage = e.toString();
			e.printStackTrace();
			Logger.e(DetailNotifikasiActivity.this, "Save tdd error", "Server response : \n"+
					result+"\nHttpRespondException message : "+e.toString());
		}
		
		catch (HttpException e) {
			errorTitle = "HttpException";
			errorMessage = e.toString();
			e.printStackTrace();
			Logger.e(DetailNotifikasiActivity.this, "Save tdd error", " : \n"+
					"\nHttpException message : "+e.toString());
		} catch (Exception e) {
			errorTitle = "Exception";
			errorMessage = e.toString();
			e.printStackTrace();
			Logger.e(DetailNotifikasiActivity.this, "Save tdd error", " : \n"+
					"\nException message : "+e.toString());
		}finally{
			DetailNotifikasiActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					if(loadingDialog != null){
						loadingDialog.dismiss();
					}
					SweetAlertDialog alert  = null;
					if(errorTitle == null){
						Log.d("[print-error]", "error title :  "+errorTitle);
						Log.d("[print-resutl]", "result value : "+result);
						/*Log.d("[result == 1]", ""+(Integer.parseInt(result.substring(0, 1)) == 1));
						Log.d("[result equals 1]", ""+(result.equals("1")));
						Log.d("[result equals ignore case 1]", ""+(result.equalsIgnoreCase("1")));*/
						if(result.substring(0, 1).equalsIgnoreCase("1")){
							alert = new SweetAlertDialog(DetailNotifikasiActivity.this, SweetAlertDialog.SUCCESS_TYPE);
							alert.setTitleText("Selamat !!"); 
							alert.setContentText("Dokumen disetujui dan telah tersimpan dalam server !!");
							alert.show();
							DatabaseHelper db = new DatabaseHelper(DetailNotifikasiActivity.this);
							NotifikasiSKPD notifikasi = db.getNotifikasi(id);
							notifikasi.setStatus(2);
							db.update(notifikasi.getId(), notifikasi);
							Log.d("[ACC-Ok]", "proses ACC berhasil, data disimpan dalam database!");
							NotificationActivity.dataChange 		= true;
							NotificationActivity.locationChange 	= location;
						}else{
							alert = new SweetAlertDialog(DetailNotifikasiActivity.this, SweetAlertDialog.ERROR_TYPE); 
							alert.setTitleText("Oops..!!");
							alert.setContentText("Terjadi kesalahan, data tidak berhasil disimpan dalam server !! ");
							alert.show();
							Logger.e(DetailNotifikasiActivity.this, "save respond error", "document failed to save!\n" +
									"url :"+url+ "\n" +
									"parameter : "+postParameters.get(0).getName()+", value :"+postParameters.get(0).getValue()+ "\n" +
									"parameter : "+postParameters.get(1).getName()+", value : "+postParameters.get(1).getValue()+"\n" +
									"\nrespond error!!!");
						}
					}else{
						alert = new SweetAlertDialog(DetailNotifikasiActivity.this, SweetAlertDialog.ERROR_TYPE); 
						alert.setTitleText("Oops..!!");
						alert.setContentText("Data tidak berhasil disimpan karena terjadi kesaalahan " +
								"dalam aplikasi atau respond dari server yang keliru !!");
						alert.show();
						Logger.e(DetailNotifikasiActivity.this, "save respond error", "document failed to save!\n" +
								"url :"+url+ "\n" +
								"parameter : "+postParameters.get(0).getName()+", value :"+postParameters.get(0).getValue()+ "\n" +
								"parameter : "+postParameters.get(1).getName()+", value : "+postParameters.get(1).getValue()+"\n" +
								"\nwith error : "+errorMessage.toString());
					}
				}
			});
		}
		
		Log.e("[error]", "cause : "+ errorTitle+", message : "+errorMessage);
		return successful;
	}
	
	
	
	/**
	 * 
	 * InnerClass SinkronisasiThread 
	 * digunakan untuk menjalankan sinkronisasi 
	 * di Thread yang terpisah dari UIMainThread
	 * 
	 */
	
	private class SaveTtdThread implements Runnable{
		private ArrayList<NameValuePair> postParameters; 
		private String url;
		
		/**
		 * @param url : alamat url untuk melakukan process httpClient
		 * @param postParameters : parameter untuk httpPost
		 */
		public SaveTtdThread(String url, ArrayList<NameValuePair> postParameters){
			this.url 			= url;
			this.postParameters = postParameters;
		}
		
		@Override
		public void run() {
			DetailNotifikasiActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					loadingDialog = new SweetAlertDialog(DetailNotifikasiActivity.this, SweetAlertDialog.PROGRESS_TYPE); 
					loadingDialog.setTitleText("Proses simpan dokumen..."); 
					loadingDialog.show();
				}
			});
			saveTtdUsingThread(url, postParameters);			
		}
		
	}
}
